package com.pcy.project.rpc;

import com.alibaba.fastjson.JSONObject;
import com.pcy.project.Constants;
import com.pcy.project.bean.GetBestBlockHashCommon;
import com.pcy.project.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 清秋
 * @email:
 * @datetime: 11:32 2021/12/15
 * @Description:
 */
public class GetBestBlockHash {

    public String getBestBlockHash() {

        //准备rpc请求的用户的身份信息
        String author = Constants.BITCOIN_RPC_USER + ":" + Constants.BITCOIN_RPC_PWD;

        //java中实现base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString( author.getBytes() );

        //准备请求头信息
        Map<String, String> header = new HashMap<>();
        header.put( "ContentType", "application/json" );
        header.put( "Authorization", "Basic " + authorBase64 );

        //准备要发送的rpc数据
        Map<String, Object> body = new HashMap<>();
        body.put( "id", 1001 );
        body.put( "method", "getbestblockhash" );
        body.put( "params", null );
        body.put( "json_rpc", "2.0" );

        //将Map转换成byte[]
        byte[] bodyBytes = JSONObject.toJSONBytes( body );

        //格式：{"id":1001,"result":xxxx,"error":null}
        String result = HttpUtils.post(
                Constants.BITCOIN_RPC_URL,
                header,
                bodyBytes );

        //对result进行json反序列化
        GetBestBlockHashCommon BestBlockHashCommon = JSONObject.parseObject( result, GetBestBlockHashCommon.class );
        return BestBlockHashCommon.result;
    }
}
